package com.hqully.smartfumehood.controller;



import com.hqully.smartfumehood.common.enums.ResultEnum;
import com.hqully.smartfumehood.common.exception.ResultException;
import com.hqully.smartfumehood.common.utils.JWTUtil;
import com.hqully.smartfumehood.common.utils.ResultVoUtil;
import com.hqully.smartfumehood.common.vo.ResultVo;
import com.hqully.smartfumehood.entity.User;
import com.hqully.smartfumehood.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Slf4j
@RestController
public class LoginController extends BaseController{

    @Autowired
    private UserService userService;
    

    @ApiOperation(value = "未登陆时跳转的接口")
    @GetMapping("/login")
    public ResultVo tologin() {
        return ResultVoUtil.error(ResultEnum.USER_LOGOUT);
    }


    @ApiOperation(value = "未授权时跳转的接口")
    @GetMapping("/unAuthorized")
    public ResultVo unAuthorized() {
        return ResultVoUtil.error(ResultEnum.NO_PERMISSIONS);
    }


    @ApiOperation(value = "登录", notes = "json对象中只需要有账号和密码")
    @PostMapping("/login")
    public ResultVo login(@RequestBody User user){

        log.info(user.getUsername(),user.getPassword());
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            throw new ResultException(ResultEnum.USER_NAME_PWD_NULL);
        }

        User currentUser = null;
        try {
            Subject subject = SecurityUtils.getSubject();

            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());

            subject.login(token);

            currentUser = (User)subject.getPrincipal();

            Long unitId = userService.findUnitByUsername(user.getUsername());

            if (unitId == null){
                currentUser.setUnitId(-1L);
            }else {
                currentUser.setUnitId(unitId);
            }

            String jwtToken = JWTUtil.createToken(currentUser);

            HashMap<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("token",jwtToken);

            return ResultVoUtil.success("登录成功",dataMap);

        } catch (AuthenticationException e) {

            return ResultVoUtil.error("用户名或密码错误");
        }








    }

    @PostMapping("/register")
    public ResultVo register(@RequestBody User user){

        String password = user.getPassword();

        String salt = new SecureRandomNumberGenerator().nextBytes().toString();

        String algorithmName = "md5";

        int times = 2;

        String encodedPassword = new SimpleHash(algorithmName,password,salt,times).toString();

        user.setPassword(encodedPassword);

        user.setSalt(salt);

        userService.addUser(user);

        return ResultVoUtil.success("insert success");
    }

    @GetMapping("/get-info")
    public ResultVo getInfo(String token){
        String username = JWTUtil.getUsername(token);

        User user = userService.findUserByUsername(username);


        HashMap<String, Object> userInfo = new HashMap<>();

        List<String> roles = new ArrayList<>();

        roles.add(user.getRole());

        userInfo.put("roles",roles);

        return ResultVoUtil.success(userInfo);

    }

    @GetMapping("/logout")
    public ResultVo logout(){

        return ResultVoUtil.success("success");

    }
}
